package muilty_thread.java_current_practice_and_kernel.cp5;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Preloader {
    private final FutureTask<ProductInfo> future = new FutureTask<ProductInfo>(() -> {
        return loadProduct();
    });
    private final Thread thread = new Thread(future);

    private ProductInfo loadProduct() throws InterruptedException {
        Thread.sleep(3000);
        return new ProductInfo("msg");
    }

    public void start(){
        thread.start();
    }

    public ProductInfo get(){
        try{
            return future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            Throwable t = e.getCause();

            throw launderThrowable(t);
        }
        return null;
    }

    public static void main(String[] args) {
        Preloader preloader = new Preloader();
        preloader.start();
        System.out.println(preloader.get());
        System.out.println("1");
        System.out.println("sdfdsafsda");
    }

    public static RuntimeException launderThrowable(Throwable t) {
        if (t instanceof RuntimeException) {
            return (RuntimeException) t;
        } else if (t instanceof Error) {
            throw (Error) t;
        } else {
            throw new IllegalStateException("lsdjfl", t);
        }
    }
}
class ProductInfo{
    private String message;

    @Override
    public String toString() {
        return "ProductInfo{" +
                "message='" + message + '\'' +
                '}';
    }

    public ProductInfo(String message) {
        this.message = message;
    }
}